<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Project\Progress;
use App\Models\SignCompany;
use App\Services\Porject\ProgressService;
use App\Traits\Admin\SuccessOrFailure;
use Illuminate\Http\Request;

class SignCompanyController extends Controller
{
    use SuccessOrFailure;

    private $permission = 'common.sign_company';


    public function index()
    {
        $this->canOrFailure($this->permission);
        $data = SignCompany::query()->orderBy('id')->get();

        return view('admin.sign_company.index', compact('data'));
    }


    public function create()
    {
        $this->canOrFailure($this->permission);
        return view('admin.sign_company.create');
    }

    public function store(Request $request)
    {
        $this->canOrFailure($this->permission);

        $attributes = $this->buildData($request);
        SignCompany::create($attributes);
        return $this->success('', route('admin.signCompany.index'));
    }

    public function edit($id)
    {
        $this->canOrFailure($this->permission);
        $sign_company = $this->getSignCompanyOrFailure($id);
        return view('admin.sign_company.edit', compact('sign_company'));
    }

    public function update(Request $request, $id)
    {
        $this->canOrFailure($this->permission);

        $sign_company = $this->getSignCompanyOrFailure($id);
        $attributes = $this->buildData($request);
        $sign_company->update($attributes);

        return $this->success('', route('admin.signCompany.index'));
    }

    public function buildData($request)
    {
        $this->validate($request,
            ['name' => 'required', 'number' => 'required'],
            ['name.required' => '请填写名称！', 'number.required' => '请填写编号！',]
        );

        return [
            'name' => $request->input('name'),
            'number' => $request->input('number'),
        ];
    }

    public function destroy($id)
    {
        $this->canOrFailure($this->permission);

        $sign_company = $this->getSignCompanyOrFailure($id);
        $sign_company->delete();
        return $this->success();
    }

    private function getSignCompanyOrFailure($id)
    {
        $sign_company = SignCompany::query()->find($id);
        if (!$sign_company) {
            response($this->failure('值不存在！'), 404)->send();
            exit;
        }
        return $sign_company;
    }
}
